import { loginAPI } from "@/apis/user";
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useCartStore } from './cartStore'
import { mergeCartAPI } from "@/apis/cart.js"
export const useUserStore = defineStore('user', () => {
    // 定义管理用户数据的state
    const userInfo = ref([]);
    const cartStore = useCartStore()
    //定义获取解构数据的action函数
    const getUserInfo = async ({ account, password }) => {
        const res = await loginAPI({ account, password });
        userInfo.value = res.result;
        // 合并购物车的操作
        await mergeCartAPI(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        // 获取最新的购物车列表
        cartStore.updateNewList()
    };
    // 退出时清除胡勇信息
    const clearUserInfo = () => {
        userInfo.value = {}
        cartStore.clearCart()
    }
    return {
        getUserInfo, userInfo, clearUserInfo
    }
}, {
    persist: true
})
